//经费管理
<template>
  <div class="module_">
    <div class="mb8">
      <div class="flex-align-center">
        <back />
        <p class="tx-r flex-1">
          <el-button class="mr8" size="small" type="primary" @click="handle(null,{},3)">申请奖励</el-button>
        </p>
      </div>
      <table class="table_ mt8">
        <tr>
          <td>学科</td>
          <td class="fb">{{info.name}}</td>
          <td>奖励</td>
          <td class="fb">{{info.bonus}}（万元）</td>
          <td>奖励余额</td>
          <td class="fb">{{info.bonus_balance}}（万元）</td>
        </tr>
      </table>
    </div>
    <el-table :data="tableData" class="flex-1" height="100%" size="medium" border highlight-current-row
      v-loading="tableLoading" stripe @sort-change="tableSortChange">
      <el-table-column align="center" v-for="(item,i) in headerList" :key="item.prop" :prop="item.prop"
        :label="item.label+(item.unit || '')" :min-width="item.width" :fixed="i === 0 ? true: false" show-overflow-tooltip
        sortable="custom">
        <template slot-scope="scope">
          <template v-if="item.prop === 'review_status'">
            <span v-if="scope.row.review_status === 2" class="c-red">{{reviewStatusObj[scope.row.review_status]}}：{{scope.row.review_comment}}</span>
            <span v-else>{{reviewStatusObj[scope.row.review_status]}}</span>
          </template>
          <template v-else>
            {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="150">
        <div class="flex-justify-end" slot-scope="scope">
          <el-tooltip  effect="dark" content="审核" placement="bottom-end" v-show="scope.row.review_status == 0">
            <el-button v-permission="{action:'经费奖励审核',effect:'delete'}" type="primary" @click="examine_btns(scope.row,1)" size="small"  icon="el-icon-help" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="修改信息" placement="bottom-end">
            <el-button size="small" @click="handle(scope.$index, scope.row,2)" icon="el-icon-edit" circle></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="bottom-end">
            <el-button v-if="scope.row.delete" size="small" type="danger" @click="deleteUser(scope.$index, scope.row)" icon="el-icon-delete"
              circle></el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <el-dialog :visible.sync="editFormVisible" width="400px" @close='dialogClose' :close-on-click-modal='false'
      :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c">{{dialogTitle}}</h2>
      <el-form autocomplete="off" label-width="100px" :model="editForm" class="form_flex">
        <el-form-item v-for="(v, i) in editHeaderList" :key="i" :label="v.label" :class="v.required ? 'tip' : ''">
          <inputSearch v-if="v.prop === 'department_name'" ref="departmentSearch" type="departments2" 
          @onChange='agentChange($event,"department_id")' :options="{discipline_id:info.discipline_id}" />
          <inputSearch v-else-if="v.prop === 'agent_name'" ref="agentSearch" @onChange='agentChange($event,"agent_id")' :middleList="middleList" />
          <el-date-picker v-else-if="v.prop === 'time'" size="medium" v-model="editForm[v.prop]" type="date"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择支出时间">
          </el-date-picker>
          <el-input v-else size="medium" :type="v.type" autosize clearable v-model="editForm[v.prop]"
            @mousewheel.native.prevent :placeholder="'请输入' + v.label" >
            <template v-if="v.prop === 'amount'" slot="append">万元</template>
          </el-input>
          <div v-if="v.prop === 'amount'" :class="[remaining >=0 ?'c-9':'c-red','amount_tip']" >可申请余额：{{remaining}}万元</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>

    <!-- 审核 -->
    <examine ref="examine" @submit='examineSubmit' :item='examine_item' /> 

  </div>
</template>

<script>
  import {
    Apievaluatefund,
    ApievaluatefundAdd,
    ApievaluatefundPut,
    ApievaluatefundDel,
    ApievaluaterankInfo,
    ApievaluatefundCheck,
  } from '@/api'
  import {debounce,adminShow} from "@/utils/index";
  import {headerList} from "../js/fundsManagement"
  import {reviewStatusObj} from '@/assets/js'
  export default {
    name: 'fundsManagement',
    computed: {
      remaining(){
        return (Number(this.info.bonus_balance) + Number(this.beforeAmount) - Number(this.editForm.amount ?? 0)).toFixed(2)
      },
      editHeaderList() {
        return headerList.filter(item => item.edit)
      }
    },
    data() {
      return {
        adminShow: adminShow(),
        reviewStatusObj,
        Apievaluatefund,
        tableData: [],
        editFormVisible: false,
        editForm: {}, //修改或者查看详情
        evaluate_rank_id: this.$route.query.id,
        pageparm: {
          page: 1,
          perPage: 20,
          total: null,
          sort_str: null,
          sort_order: 'desc',
          evaluate_rank_id: this.$route.query.id,
        },
        tableLoading: false,

        btnLoading: false,

        headerList,
        rules: ['department_id','time','amount','reason'],

        examine_id: null, //审核id
        examine_item: {},

        middleList: [],
        dialogTitle: '',

        info: {},
        beforeAmount:0
      }
    },
    mounted() {
      this.getInfo()
      this.getList()
    },
    methods: {
      examine_btns(item,i){
        this.examine_id = item.id
        this.$refs.examine.examineShow = true
      },
      examineSubmit(options){
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        options.id = this.examine_id
        ApievaluatefundCheck(options,options.id).then(res => {
          this.getList()
          this.getInfo()
        }).catch(()=>{
          this.$message.error('服务器错误，请重新提交');   
        }).finally(()=>{
          loading.close()
        })
      },
      agentChange(id,ele){
        this.editForm[ele] = id
      },
      tableSortChange(column) {
        if (column.order === "descending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "desc";
        } else if (column.order === "ascending") {
          this.pageparm.sort_str = column.prop;
          this.pageparm.sort_order = "asc";
        } else {
          this.pageparm.sort_str = null;
          this.pageparm.sort_order = null;
        }
        this.getList()
      },
      
      //分页
      callFather(pageparm) {
        this.pageparm.page = pageparm.page
        this.pageparm.perPage = pageparm.perPage
        this.getList()
      },
      getInfo(){
        ApievaluaterankInfo(this.evaluate_rank_id).then(res=>{
          this.info = res.data
        })
      },
      getList() {
        this.tableLoading = true
        Apievaluatefund(this.pageparm).then(({data,page}) => {
          this.tableData = data || []
          this.pageparm.total = page.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      handle(index, value, i) {
        this.editForm = {...value}
        this.beforeAmount = value.amount || 0
        this.editFormVisible = true
        if (i == 2) {
          this.dialogTitle = '修改奖励'
          this.$nextTick(() => {
            this.$refs.departmentSearch[0].departments_id = value.department_id
            if(value.agent_id) this.middleList = [{employees_id: value.agent_id,employee: {name: value.agent_name}}]
          })
        } else {
          this.dialogTitle = '申请奖励'
          this.$nextTick(()=>{
            if(!this.adminShow) {
              this.editForm.department_id = this.$refs.departmentSearch[0].departments_id = this.$store.state.userInfo.department_id
            }
          })
        }
      },

      dialogClose() {
        this.$refs.departmentSearch[0].clear()
        this.$refs.agentSearch[0].clear()
      },
      deleteUser(index, value) {
        this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          ApievaluatefundDel(value.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
            this.getInfo()
          }).finally(() => {
            loading.close()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      submit: debounce(function () { //提交  修改或新增
        const options = {...this.editForm}
        for (const key of this.rules) {
          if (!options[key] && options[key] !== 0) {
            this.$message({
              type: 'error',
              message: '必填信息请填写完整！'
            });
            return
          }
        }
        if(Number(options.amount) <= 0){
          this.$message.error('请输入正确申请金额')
          return
        }
        if(this.remaining < 0){
          this.$message.error('申请金额不可大于奖励余额')
          return
        }
        options.evaluate_rank_id = this.evaluate_rank_id
        this.btnLoading = true
        if (options.id) { //有ID就是修改
          ApievaluatefundPut(options, options.id).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.editFormVisible = false
            this.getList()
            this.getInfo()
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '修改失败!'
            });
          }).finally(() => {
            this.btnLoading = false
          });
        } else {
          ApievaluatefundAdd(options).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.editFormVisible = false
            this.getList()
            this.getInfo()
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '添加失败!'
            });
          }).finally(() => {
            this.btnLoading = false
          });
        }
      }, 800, true),
    },

  }
</script>
<style lang="less" scoped>
.amount_tip{
  line-height: 1;
}  
</style>